var $ = jQuery;
/* image center & Crop */
jQuery.fn.imageCrop = function(){
	var $ = jQuery;
	return this.each(function(){
		
        $(this).parent().css({
			"text-align": "center",
			"vertical-align": "middle",
			"display" : "block",
            "overflow": "hidden"
		});
		
		var image = this;
		var newimage = new Image();
		newimage.src = $(image).attr("src");
		newimage.onload = function(){
			image_size = {width: this.width,height: this.height};
			parent_size = { width: $(image).parent().width(),height: $(image).parent().height() };
			var new_size = {
				width: parent_size.width, 
				height: parent_size.width*(image_size.height/image_size.width)
			};
			if(new_size.height < parent_size.height){
				new_size = {
					width: parent_size.height*(image_size.width/image_size.height), 
					height: parent_size.height
				};
			}
			
			$(image).width(new_size.width);
			$(image).height(new_size.height);
			$(image).css({
			     "margin":"0 auto",
                 "max-width": "none",
                 "max-height": "none" 
            });
			if(new_size.height>parent_size.height){
				$(image).css({
					"margin-top":((parent_size.height-new_size.height)/2)+"px"
				});
			}else{
  	             $(image).css({
					"margin-left":((parent_size.width-new_size.width)/2)+"px"
				});
			}
		}		
	});
}

/* image center */
jQuery.fn.imageCenter = function(){
	var $ = jQuery;
	return this.each(function(){
		$(this).parent().css({
			"text-align": "center",
			"vertical-align": "middle",
			"display" : "block"
		});
		var image = this;
		
		var _image = new Image();
		_image.src = $(this).attr("src");
		_image.onload = function(){
			image_size = {width: this.width,height: this.height};
			parent_size = { width: $(image).parent().width(),height: $(image).parent().height() };
			var new_size = {
				width: parent_size.width, 
				height: parent_size.width*(image_size.height/image_size.width)
			};
			if(new_size.height>parent_size.height){
				new_size = {
					width: parent_size.height*(image_size.width/image_size.height), 
					height: parent_size.height
				};
			}
			
			$(image).width(new_size.width);
			$(image).height(new_size.height);
			$(image).css({"margin":"0 auto" });
			if(new_size.height<parent_size.height){
				$(image).css({
					"margin-top":((parent_size.height-new_size.height)/2)+"px"
				});
			}
		}
	});
}

/*================================Main===============================*/
jQuery(function( $ ){

/*	$('.datepicker').datepicker({
			"dateFormat" :"dd/mm/yy",
			"changeYear" : true,
			"changeMonth" : true,
			"yearRange" :"c-50:c"
		});*/
	// show first child size
	
		
	 
	$("#op-size-child .hide:first").show();
	
	$(".bg-size-others img").imageCrop();

    // Show comment
    var hash = window.location.hash;
    if(hash!=""){
        $("a[href='#review']").tab("show");
    }
    
    // popover
    $("[data-toggle='popover']").popover();
    
    
    $('#myTab a').click(function (e) {
		e.preventDefault();
		$(this).tab('show');
	})

    /* image center */
	$(".image-center").imageCenter();
    /* image crop */
	$(".image-crop").imageCrop();
	
    /* form login */
	
    $('.fancybox').fancybox();
	
	$(".fancybox2").fancybox({
		width: false
	});
	
	/* mail gia */
	
	$("#csdmail").click(function(){
		 setTimeout(function() {
						$(".mess_mailsa").fadeIn();	
					}, 2000);	
					
		 setTimeout(function() {
						$(".mess_mailsa").fadeOut();	
					}, 8000);
		return false;			
	})
	
	/* user-coupon */
	$("#user-coupon").click(function(){
		var flag=$(this).prev().val();
		var val_hide=$("#value-coupon").val();
		var val_main=$("#code_coupon").val();
		var check_string=val_main.match("NEW");
		if(check_string) // if word "NEW" in strings
		{
			if(flag==0 || flag=="")
			{
				$(this).next().find(".error-coupon").fadeIn("slow",function(){
					 setTimeout(function() {
							$(".error-coupon").fadeOut();	
						}, 5000);
				});
			}
			else
			{
				var value=$("#value-coupon").val();
				var value_main=	$("#code_coupon").val();
				if(value_main=="")
				{
					$(".empty_cop").fadeIn("slow",function(){
							setTimeout(function() {
								$(".empty_cop").fadeOut();	
						}, 2500);
					})
				}
				else
				{
					if(value!=value_main)
					{
						
						$(".sai_cop").fadeIn("slow",function(){
								setTimeout(function() {
									$(".sai_cop").fadeOut();	
							}, 2500);
						})
					}
					else
					{
						var user=$("#user-coupon").val();
						$("#icon-coupon").fadeIn("slow");
						var data={action:"ajax_coupon",id_user:user,flag_data:"coupon_user"};
						$.post(ajaxurl,data,function(rdata){
						  if(rdata.flag=='new')
						  {	
						   $(".success-coupon").fadeIn("slow");
						   $("#icon-coupon").fadeOut("slow");	
							       $("#price_before_copoun").text(rdata.price);
								   setTimeout(function() {
									  $("#price_after_copoun").fadeIn("slow");	
								   }, 2000);
						  }
						},'json')
					}
				}
			}
		}
		else
		{
			
			var val_main=$("#code_coupon").val();
			if(val_main==""|| val_main==null)
			{
				$(".empty_cop").fadeIn("slow");
			}
			else
			{
				$("#icon-coupon").fadeIn("slow");
				var data={action:"ajax_coupon",flag_data:"coupon_birthay",data_coupon:val_main};
				$.post(ajaxurl,data,function(rdata){
				if(rdata.impo==true)
					{
						if(rdata.flag=='birthay')
						{
							$(".success-coupon").fadeIn("slow");
							$("#icon-coupon").fadeOut("slow");
							$("#price_before_copoun").text(rdata.price);
							setTimeout(function() {
										  $("#price_bithday").text(rdata.tmp_price);	
										  $("#price_after_copoun_birthay").fadeIn("slow");	
							}, 2000);
						}
				    }
				else
					{
						$("#icon-coupon").hide();
						$(".error-coupon").fadeIn("slow",function(){
							 setTimeout(function() {
								$(".error-coupon").fadeOut();	
							}, 5000);
						});
					}
				},'json');
			}
		}
	})
	/* user-coupon */
	
	
	
	$(".fancybox2").live("click",function(){
		var id_object = this.rel;
		$("#"+id_object).click();
	});
	
    
    /* form login */
    $("#form-login form,#form-login2 form").submit(function(){
        var form = this;
        var link = form.action;
        var data = $(this).serializeArray();
        $(".ajaxload").show();
        $.post(link,data,function(rdata){
            if(rdata.error==false){
                $(".ajaxload").hide();
				if(rdata.link!=null) window.location = rdata.link; 
            }else{
                $(form).find(".alert").remove();
                $(form).find(".confirm").append(rdata.alert);
            }
            $(".ajaxload").hide();
        },'json');
        return false;
    });
    
    
    var total_width = $("#product-title").width();
    var left_width = $("#product-title .fl").width();
    $("#product-title .fr").css("width",( Math.round( ( (total_width-left_width)*100 )/total_width )-5 + "%") );
    
	    $(".lists-color li a").click(function(){
        $(".lists-color").find(".active").removeClass("active");
        $(".lists-color").find("input").attr("checked",false);
        
        $(this).parent().addClass("active");

        $(this).find("input").attr("checked",true);        
        return false;
    });
    
    
     $('#myTab a').click(function (e) {
        e.preventDefault();
        $(this).tab('show');
    })
    
    // Mua ngay
    $(".buy-now").bind("click",function(){
        
        // Get size
        var input_size = $(".chose-size").find("input:checked");
        var size_value = input_size.val();
        var size_label = input_size.next("label").text();
        
        // Get color
        var input_color = $(".lists-color").find("input:checked");
        var color_value = input_color.val(); 
        var color_label = input_color.parent("a").attr("title");
        
        // Get quantity
        var qty_value = $(".quantity").find("input[name='quantity']").val();
        
        // Add to popup
        $(".form-buy-now").find("input[name='size']").val(size_value);
        $(".form-buy-now").find(".display-size").text(size_label);
        
        $(".form-buy-now").find("input[name='color']").val(color_value);
        $(".form-buy-now").find(".display-color").text(color_label);
        
        $(".form-buy-now").find("input[name='quantity']").val(qty_value);
        $(".form-buy-now").find(".display-quantity").text(qty_value);
        
        
    });
    
    // change address
    $("input[name='other_address']").change(function(){
        var value = this.value;
        if(value=='yes'){
            $(".thongtin-nguoinhan").show();
            $(".custom_receiv").show();
        }else{
            $(".thongtin-nguoinhan").hide();
        }
    });
    var chose = $('.chose-otheraddress input:checked').val();
    if(chose=='yes'){
        $(".thongtin-nguoinhan").show();
        $(".custom_receiv").show();
    }
    
    // Change payment
    $(".change-payment").click(function(){
		
        $(".table-payment td.active").removeClass("active");
        $(".table-payment input[name='select_payment']").attr("checked",false);
        $(this).prev("input").attr("checked",true);
        $(this).parent("td").addClass("active");
		
		if($(this).prev("input").val()==144)
		{
			$(".btn-checkout-finished").fadeOut("fast",function(){
				$(".btn-checkout-finished-ngan-luong").fadeIn("slow");
			})
		}
		else
		{
			$(".btn-checkout-finished-ngan-luong").fadeOut("",function(){
				$(".btn-checkout-finished").fadeIn("slow");
			})
		}
        return false;
    });
    
    $(".btn-checkout-finished").click(function(){
        var payment_value = $("input[name='select_payment']:checked").val();
		loading = $("<div class='load-small fl'/>").prependTo($(this));
		
		
        $.post(this.href,{'payment':payment_value},function(rdata){
			loading.remove();
           window.location = rdata.return_link;
		//  $("#txast_mail").html(rdata.content);
        },'json');
		
        return false;
    });
	
	var deftop=$("#main-menu").offset(); 
		 $(window).scroll(function () {
		  var heightscroll = $(window).scrollTop();
		  moc=deftop;
		  if(heightscroll>=(moc.top)) {
			 $("#main-menu").addClass("fixedmenu");     
		  }else{
		   $("#main-menu").removeClass("fixedmenu");   
		  }
	 });
	 
	$(".to-top a").click(function(){
		$("html, body").animate({ scrollTop: 0 }, 600);
		return false;
	});
    
    
    $(".chose-qty").live("keydown", function (e){
        var key = e.charCode || e.keyCode || 0 ;
        return (key == 8 ||key == 9 ||key == 46 ||(key >= 37 && key <= 40) ||(key >= 48 && key <= 57) ||(key >= 96 && key <= 105));
    });
    
});

/**
 * Ham mua ngay
 */
function buy_now(f){
    var $ = jQuery;
    var sdata = $(f).serializeArray();
	$(".ajaxload").show();
	$(f).find(".alert").remove();
    $.post(f.action,sdata,function(rdata){
        $(f).prepend(rdata.message);
		$(".ajaxload").hide();
    },'json');
    return false;
}

/**
 * Them vao gio hang
 */
 
 function add_to_cart(f,obj){
    var $ = jQuery;
    var size = $(f).find("input[name='size']:checked").val();
    if( size==undefined){
        $("#form-sub .popover").fadeIn(300);
		setTimeout(function() {
    		$("#form-sub .popover").fadeOut();	
		}, 2500);
        return false; 
    }
    $(f).submit();
    return false;
 }
 
 
 
 
 
 
 /**
 * Add wish list
 */
function add_wish_list(f,obj)
{
	var $ = jQuery;
    var size = $(f).find("input[name='size']:checked").val();
	if(size==undefined)
	{
		$(obj).parents("#form-sub").find(".popwish").fadeIn();
		setTimeout(function() {
    		$(obj).parents("#form-sub").find(".popwish").fadeOut();
		}, 2000);
	}
	else
	{
		var check_login=$(obj).attr("class");
		if(check_login=="")
		{	
			var _mess=$(obj).parents("#form-sub").find("#mess_login")
			_mess.fadeIn();
			setTimeout(function() {
    			_mess.fadeOut();
			}, 3000);
		}
		else
		{	
			$(obj).find("#heart2").hide();
			$(obj).next().fadeIn("slow");
			var id=$(f).find("input[name='ID']").val();
			var size=$(f).find("input[name='size']:checked").val();
			var user=$(obj).attr("rel")
			var _time=$(obj).parents("#form-sub").find("#time_product").val();
			var data={action:"add_wish_list",id_product:id,id_size:size,id_user:user,time:_time};
			$.post(ajaxurl,data,function(rdata){
				$(obj).next().fadeOut("slow");
				$(obj).find("#heart2").show("slow");
				var _ompo=$(obj).parents("#form-sub").find(".sucss_wish")
				_ompo.fadeIn(2000);
				setTimeout(function() {
    			_ompo.fadeOut();
			}, 10000);		
			})
		}
	}
	return false;
}

 /**
  * remove wishlist
  */
function remove_list_tmp(f)
{
	var $ = jQuery;
	$(f).next().show("slow");
	$(f).prev().fadeIn(2000);	
	return false;
}
function remove_list_yes(f)
{
	var $ = jQuery;
	var size= $(f).attr("id");
	var user= $(f).attr("title");
	var data ={action:"remove_list_yes",id_size:size,id_user:user};
	$(f).parents(".mess_list").css({"opacity":"0.7"});
	$(f).parents(".remove_list").find(".icon_remove_wish").hide();
	$(f).parents(".remove_list").find(".icon_remove_list").fadeIn();
	$.post(ajaxurl,data,function(){
		$(f).parents(".remove_list").find(".icon_remove_wish").show();	
		$(f).parents(".remove_list").find(".icon_remove_list").hide();	
		$(f).parents(".remove_list").find(".mess_list").fadeOut("slow",function(){
				$(this).parents("tr").fadeOut("slow",function(){
					$(this).remove();
			})
		})
			
	})
	return false;
}
function remove_list_no(f)
{
	var $ = jQuery;
	$(f).parents(".remove_list").find(".icon_remove_wish").hide(10);
	$(f).parents(".mess_list").fadeOut("slow");
	
	return false;
}


 /**
  * Xoa san pham khoi gio hang
  */
 function del_cart(o){
    var $ = jQuery;
    $.post(o.href,{key:o.rel},function(rdata){
        $(".page-cart .subtotal").text(rdata.subtotal_price);
        $(".cart-total").text(rdata.total);
        $(o).parents("tr").fadeOut("slow",function(){
            $(this).remove();
        });
        if($(".table").children("tbody").find("tr").length<=0){
            window.location = window.location;
        }
    },'json');
    return false;
 }
 
 
 /**
  * Cap nhat so luong gio hang
  */
 function update_qty_cart(o){
    var $ = jQuery;
    var load = $(o).parents("td").find(".cart-loading");
    var input_qty = $(o).parents('.qty').find('.cart-qty');
    if(o.rel=="plus"){
        input_qty.val(parseInt(input_qty.val())+1);
    }else{
        input_qty.val(parseInt(input_qty.val())-1);
    }
    load.show();    
    var cart_index = $(o).parents("tr").find("input[name='cart_index']").val();
    var car_qty = $(o).parents('.qty').find("input.cart-qty").val();
    $.post(o.href,{key:cart_index,qty:car_qty},function(rdata){
        $(".page-cart .subtotal").text(rdata.subtotal_price);
        $(".cart-total").text(rdata.total);
        $(o).parents("tr").find('.total_price').text(rdata.total_price);
        load.hide();
    },'json');
    return false;
 }
 
 
 /**
  * Submit form checkout
  */
  function submit_form_checkout(f){
    var $ = jQuery;
    var error = false;
    $(f).find(".required").each(function(){
        if(this.value==""){
            $(this).parents(".control-group").addClass("error");
            error = true;
        }else{
            $(this).parents(".control-group").removeClass("error");
        }
    });
    if(error==false){
        f.submit();   
    }else{
        $("html,body").animate({scrollTop:$("#form_customer").offset().top-200},500);
        $("input[name='buy_fullname']").focus();
    }
    return false;
  }

/**
 * Chon size
 */
function product_chose_size(o, size_id ){
    var $ = jQuery;
    var parent = $(o).parent();
	var _check=$(o).attr("class");
	var no_check=_check.substr(-9,9);
	if(no_check=="no-active")
		return false;
	else {
		parent.find("label.labelcolor").removeClass("active");
		$(o).addClass("active");
		var point=".size_"+size_id;
		var parents=$(o).parents(".lop");
		parents.find(".opois").each(function(index, element) {
			$(element).hide();
		});
		$(point).fadeIn("fast");
	}
}
 
 /**
 * Chon mau
 */
function product_chose_color(o ){
    var $ = jQuery;
    $(".chose-qty").hide();
    $(o).next(".chose-qty").show();
    $(o).parents(".row-size").find("label").removeClass("active");
    $(o).addClass("active");
    $(".content-choose-size").find(".alert-error").hide();
    $(".chose-qty").each(function(){
        this.value = 1; 
    });
}
/**
 * Kiem tra so luong
 */
function check_in_store(obj){
    var $ = jQuery;
    var max = $(obj).attr("max");
    var val = parseInt(obj.value);
    var alert = $(obj).parents(".content-choose-size").find(".alert-error");
    if(val>max){
        alert.fadeIn("slow");
        alert.addClass("out-store");
    }else{
        alert.fadeOut("hide");
        alert.removeClass("out-store");
    }
}

/**
 * Select size child
 */
function select_size_child(f)
{
	var $ =jQuery;
	var point="#"+$(f).val();
	var parent_each=$(f).parents(".span3").next().find(".hide");
	parent_each.each(function(index, element) {
      	var id="#"+$(element).attr("id");
		if(id==point)
		{
		  $(f).parents(".span3").next().find(point).fadeIn();
		}
		else
		{
			$(element).hide();
		}
    });
}

/**
 * Select size child
 */
function check_advan(f)
{
 var $=jQuery;
 var _email=$("#email_avand").val();
 var data={action:"ajax_email_advand",email:_email};
 $.post(ajaxurl,data,function(rdata){
 if(rdata.error==0)
	 {
		$("#form-wysija-html5296e5ab999b7-3").css({"display":"none !important"});
		alert(rdata.mess);
	 }
	 else
	 {
		$("#form-wysija-html5296e5ab999b7-3").css({"display":"none !important"}); 
	 }
 },'json')

return false;
}

 
 /**
 * //@author: phongnd
 * Add to cart
 */ 
 function add_to_order_cart(form, obj)
 {
    var $ = jQuery;
    $(form).submit();
 }
 
 /**
  * //@author: phongnd
  * Cap nhat so luong gio hang
  */
 function update_order_qty_cart(name_object,command){
    var $ = jQuery;
	var car_qty;
	
   // var load = $(name_object).parents("tr").find(".cart-loading");
    var input_qty = $(name_object).parents("tr").find("#txtQty");
    var input_unit_price = $(name_object).parents("tr").find("input[name='unit_price']");
	var car_UnitPrice = parseInt(input_unit_price.val());
    if(command=="add"){//name_object.rel
        car_qty = parseInt(input_qty.val())+1;
    }else{
        car_qty = parseInt(input_qty.val())-1;
    }
	
	//update HOT
	$(name_object).parents("tr").find("#txtQty").val(car_qty);
	// var total_price = String(car_qty*car_UnitPrice); //String - caption - viet hoa
	$(name_object).parents("tr").find("#txtTotalPrice").text(String(car_qty*car_UnitPrice) + " $$$");
	
    //load.show();    
    var cart_index = $(name_object).parents("tr").find("input[name='cart_index']").val();
    
	$.post(name_object.href,{key:cart_index,qty:car_qty},function(rdata){
		
        // $(".cart-total").text(rdata.total);
        // load.hide();
    },"json");
    return false;
 }
  